package com.zekdot.userclient.util;

import com.zekdot.userclient.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Create by zekdot on 20-3-19.
 */
@Service
public class LogUtil {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 根据异常写入消息队列
     * @param e
     */
    public void writeError(Exception e){
        writeError(getExceptionInfo(e));
    }

    /**
     * 获取异常详细信息
     * @param e
     * @return
     */
    public String getExceptionInfo(Exception e){
        String packageName = LogUtil.class.getPackage().toString();
        packageName = packageName.substring(8,packageName.length() - 5);
        StringBuilder sb = new StringBuilder();
        sb.append("得到了以下的错误信息").append(e.getMessage()).append("\r\n");
        sb.append("可以定位到具体代码行数 \r\n");
        for(StackTraceElement s:e.getStackTrace()){
            if(s.toString().contains(packageName))
                sb.append("\tat ").append(s).append("\r\n");
        }
        return sb.toString();
    }

    /**
     * 写一条信息到消息队列中
     * @param content 消息内容
     */
    public void writeInfo(String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        map.put("type",0);
        rabbitTemplate.convertAndSend("LogExchange","LogRouting",map);
    }

    /**
     * 写一条错误到消息队列中
     * @param content 消息内容
     */
    public void writeError(String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        map.put("type",1);
        rabbitTemplate.convertAndSend("LogExchange","LogRouting",map);
    }
}
